package cn.wildfirechat.message;

import android.os.Parcel;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import cn.wildfirechat.message.core.ContentTag;
import cn.wildfirechat.message.core.MessagePayload;
import cn.wildfirechat.message.core.PersistFlag;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

import static cn.wildfirechat.message.core.MessageContentType.MESSAGE_CARD_TYPE_FEED;

/**
 * 发送名片
 */

@ContentTag(type = MESSAGE_CARD_TYPE_FEED, flag = PersistFlag.Persist_And_Count)
public class CardMessageContent extends MessageContent {
    public UserInfo getInfo() {
        return info;
    }

    public void setInfo(UserInfo info) {
        this.info = info;
    }

    private UserInfo info;

    public CardMessageContent(UserInfo info) {
        this.info = info;
    }

    public CardMessageContent() {
    }

    @Override
    public MessagePayload encode() {
        MessagePayload messagePayload = new MessagePayload();
        try {
            JSONObject objWrite = new JSONObject();
            objWrite.put("userId",info.uid);
            messagePayload.content = objWrite.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return messagePayload;
    }

    @Override
    public void decode(MessagePayload payload) {
        if (!TextUtils.isEmpty(payload.content)) {
            try {
                if (payload.content != null) {
                    JSONObject jsonObject = new JSONObject(payload.content);
                    this.info = ChatManager.Instance().getUserInfo(jsonObject.optString("userId"), false);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    protected CardMessageContent(Parcel in) {
        super(in);
        this.info = in.readParcelable(UserInfo.class.getClassLoader());
    }


    @Override
    public String digest(Message message) {
        return "个人名片";
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeParcelable(this.info, flags);
    }

    public static final Creator<CardMessageContent> CREATOR = new Creator<CardMessageContent>() {
        @Override
        public CardMessageContent createFromParcel(Parcel source) {
            return new CardMessageContent(source);
        }

        @Override
        public CardMessageContent[] newArray(int size) {
            return new CardMessageContent[size];
        }
    };
}
